import { IBizLabTemplate } from "@ibizlab/template";
import { kebabCase, upperFirst } from 'lodash';

/**
 * 导入插件助手 {{ImportPlugin 'form' ctrl}} {{ImportPlugin 'grid' ctrl}}
 *
 * @export
 * @class ImportPlugin
 */
export class ImportPlugin {
  /**
   * Creates an instance of ImportPlugin.
   * @param {IBizLabTemplate} template
   * @memberof ImportPlugin
   */
  constructor(template: IBizLabTemplate) {
    template.engine.registerHelper("importPlugin", (...args: unknown[]) => {
      const type = args[0];
      const ctrl = args[1] as any;
      let result: string = "";
      if (type === "form") {
        const pluginArray: string[] = [];
        const formImport = (detail: any) => {
          if (detail.psSysPFPlugin && detail.psSysPFPlugin.pluginCode) {
            if (pluginArray.indexOf(detail.psSysPFPlugin.pluginCode) === -1) {
              pluginArray.push(detail.psSysPFPlugin.pluginCode);
            }
          }
          if (detail.psDEFormDetails && detail.psDEFormDetails.length > 0) {
            detail.psDEFormDetails.forEach((item: any) => {
              formImport(item);
            });
          }
        };
        ctrl.psDEFormPages.forEach((formPage: any) => {
          if (formPage.psDEFormDetails && formPage.psDEFormDetails.length > 0) {
            formPage.psDEFormDetails.forEach((item: any) => {
              formImport(item);
            });
          }
        });
        pluginArray.forEach((plugin: string, index: number) => {
          result += `${index !== 0 ? "\n" : ""}import ${upperFirst(
            plugin
          )} from "@plugins/ctrl-item/${kebabCase(plugin)}/${kebabCase(
            plugin
          )}.vue";`;
        });
      }
      return result;
    });
  }
}
